package com.ridbor001.demo.servlet;

import com.ridbor001.demo.bean.RDBGrade;
import com.ridbor001.demo.bean.RDBTeacher;
import com.ridbor001.demo.service.RDBGradeService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Optional;

@WebServlet("/updateGrade")
public class RDBUpdateGradeServlet extends HttpServlet {
    RDBGradeService gradeService = new RDBGradeService();
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        RDBTeacher teacher = (RDBTeacher) req.getSession().getAttribute("user");
        String gradeId = req.getParameter("gradeId");

        // 查找要修改的成绩
        Optional<RDBGrade> target = null;
        try {
            target = gradeService.getGradeById(gradeId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        if (target.isPresent()) {
            RDBGrade grade = target.get();
            // 更新成绩
            grade.setDailyScore(Double.parseDouble(req.getParameter("dailyScore")));
            grade.setStageScore(Double.parseDouble(req.getParameter("stageScore")));
            grade.setFinalScore(Double.parseDouble(req.getParameter("finalScore")));

            resp.sendRedirect("gradeDetail.jsp?gradeId=" + gradeId);
        } else {
            resp.sendError(404, "未找到指定成绩记录");
        }
    }
}